package com.yami.shop.nft.common.listener;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.ZteFileUploadEvent;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.nft.common.model.NftApplyImg;
import com.yami.shop.nft.common.service.NftApplyImgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 中兴文件上传事件
 */
@Component("defaultZteProductListener")
@Slf4j
@AllArgsConstructor
public class ZteProductListener {

    private final ShopConfig shopConfig;

    private final NftApplyImgService nftApplyImgService;

    @Async
    @EventListener(ZteFileUploadEvent.class)
    public void updateZteFileListener(ZteFileUploadEvent event) throws Exception {
        // 获取配置 -- 中兴上传接口
        String uploadUrl = shopConfig.getZteFileUpload().getUploadUrl();
        String apiKey = shopConfig.getZteFileUpload().getApiKey();
        JSONObject attrData = JSONObject.parseObject(event.getAttrData());
        if (Objects.equals(event.getEsOperationType(), EsOperationType.UPDATE)) {
            // 删除 ZTE 文件
            String cloudRenderingId = attrData.getString("cloudRenderingId");
            String body = HttpRequest.delete(uploadUrl + "/api/content/files?apikey=" + apiKey + "&contentId=" + cloudRenderingId).execute().body();
            JSONObject jsonBody = JSONObject.parseObject(body);
            if (!jsonBody.getString("code").equals("0")) {
                throw new YamiShopBindException("yami.zte.upload.delete.error");
            }
        }
        // 1、获取文件流
        String resourcesDomainName = shopConfig.getDomain().getResourcesDomainName();
//        AttachFile attachFile = attachFileService.getById(attrData.getLongValue("cloudRendering"));

        // 2、获取中兴上传地址
        JSONObject postData = new JSONObject();
        postData.put("contentName", event.getFileName());
        postData.put("renderType", "0");
        postData.put("contentType", "0");
        postData.put("resourceWeight", "");
        postData.put("description", "");
        String uploadDody = HttpRequest.post(uploadUrl + "/api/content/upload-address?apikey=" + apiKey).body(postData.toJSONString()).execute().body();
        // 3、获取返回 contentId
        JSONObject uploadData = JSONObject.parseObject(JSONObject.parseObject(uploadDody).getString("data"));
        String uploadFileUrl = uploadData.getString("uploadUrl");
        String contentId = uploadData.getString("contentId");
        attrData.put("cloudRenderingId", contentId);
        // 4、上传文件
        URL url = new URL(resourcesDomainName + attrData.getString("sourceFile"));
        File file = File.createTempFile(UUID.randomUUID().toString(),attrData.getString("sourceFile"));
        FileUtils.copyURLToFile(url, file);
//        InputStreamResource
        Map<String, Object> param = new HashMap<>();
        param.put("files", file);
        String body = HttpRequest.post(uploadFileUrl).header("Content-type", "multipart/form-data").form(param).execute().body();
        file.delete();
        // 5、修改币关联信息 添加ZTE返回文件ID
        LambdaUpdateWrapper<NftApplyImg> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(NftApplyImg::getImgUrl, attrData.toJSONString());
        lambdaUpdateWrapper.eq(NftApplyImg::getId, event.getProdId());
        nftApplyImgService.update(lambdaUpdateWrapper);
    }
}
